<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title><%= title %></title>
    <script type="text/javascript" src="/javascript/lib/jQuery-3.3.1.js"></script>
</head>
<body>
    <div>
        <video id="firstVideo" src="/video/movie.mp4" controls="controls">
            your browser does not support the video tag
        </video>
        <button id="snap">Snap Photo</button>
        <canvas id="canvas" width="640" height="480"></canvas>
        <button id="getData">获取数据</button>
        <hr>
        <video id="liveVideo" controls>
            <!--<source src="http://devimages.apple.com/iphone/samples/bipbop/masterplaylist.m3u8" type="application/vnd.apple.mpegurl" />-->
            <p class="warning">Your browser does not support HTML5 video.</p>
        </video>
        <hr>

    </div>
    <script type="text/javascript">
        /**
         *   测试fetch函数
         */
        $('#getData').click(function(){
            fetch('http://localhost:3009/user').then((res) => {
                return res.json()
            }).then( data => {
                console.log('data',data)
            })
        })


        /**
         *    开发文档
         *    https://www.villainhr.com/page/2017/03/31/%E5%85%A8%E9%9D%A2%E8%BF%9B%E9%98%B6%20H5%20%E7%9B%B4%E6%92%AD
         */
        const LE = (function () {
            let buf = new ArrayBuffer(2);
            (new DataView(buf)).setInt16(0, 256, true);  // little-endian write
            return (new Int16Array(buf))[0] === 256;  // platform-spec read, if equal then LE
        })();
        console.log('当前支持Little-Endian:',LE)


        /**
         * 将底层的流和video.src 连接   一旦两者之间连接以后，该对象就没用了
         * 创建实例是同步的，但是底层流和video.src连接是异步的
         * MS 提供了一个 sourceopen 事件， 来给我们进行异步处理
         * 一旦连接之后， URL Object 就没用， 出于节省内存的目的
         * 使用 URL.revokeObjectURL(vidElement) 来销毁 URL object
         * 自适应流媒体传输（二）——为什么要使用fragmented MP4 ---视频格式
         */
        let vidElement = document.querySelector('#liveVideo');

        if (window.MediaSource) {

            // 创建 WS实例
            let mediaSource = new MediaSource();
            console.log('创建时MS的状态', mediaSource.readyState)

            // 连接video
            vidElement.src = URL.createObjectURL(mediaSource);
            console.log('连接后MS的状态', mediaSource.readyState)

            // 监听资源开启
            mediaSource.addEventListener('sourceopen', sourceOpen);

        } else {
            console.log("The Media Source Extensions API is not supported.")
        }

        function sourceOpen(e) {
            console.log('由close-->end时MS的状态',e.target.readyState)
           // 销毁对象
            URL.revokeObjectURL(vidElement.src);

            //设置音视频的编/解码格式
            let mime = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
            let mediaSource = e.target;
            let sourceBuffer = mediaSource.addSourceBuffer(mime);

            // 然后异步拉取相关的视频流
            // let videoUrl = '/video/movie.mp4';
            let videoUrl = '/video/frag_bunny.mp4';
            // let videoUrl = '/video/bear.png';
            fetch(videoUrl)
                .then(res => {
                    return res.arrayBuffer();
                })
                .then(arrayBuffer => {

                    // 将数据添加进 video 对象中
                    console.log('后端拿取到的数据', arrayBuffer)
                    sourceBuffer.appendBuffer(arrayBuffer);

                    // 添加数据完毕后 进行播放，最后断开连接
                    // updateend -->  append()/remove() 已经结束
                    sourceBuffer.addEventListener('updateend', function(e) {

                        console.log('获取的数据完毕')
                        console.log('> -----------状态信息------------ <')
                        console.log('updating',sourceBuffer.updating)
                        console.log('readyState',mediaSource.readyState)
                        console.log('> -----------音视频识别情况------------ <')
                        console.log('audio/mp3',MediaSource.isTypeSupported('audio/mp3'))
                        console.log('video/mp4',MediaSource.isTypeSupported('video/mp4'))
                        console.log('video/mp4-imp',MediaSource.isTypeSupported('video/mp4; codecs="avc1.4D4028, mp4a.40.2"'))
                        console.log('> -----------end------------ <')

                        // 是否有持续更新的流
                        console.log('更新流', sourceBuffer.updating)
                        if (!sourceBuffer.updating && mediaSource.readyState === 'open') {

                           //没有，则断开连接
                           //  mediaSource.endOfStream();
                            // firstVideo.play()

                            // 设置当前流播放时间
                            // mediaSource.duration = 120
                            vidElement.play()
                            console.log('开始播放')
                        }
                    });
                });
        }

        // 自拍照片 -- 获取canvas图片并将其上传
        function convertCanvasToImage() {
            let a = document.getElementById("canvas");
            let image = new Image();
            image.src = a.toDataURL("image/png");
            return image.src;
        }
        document.getElementById('snap').onclick = function () {

            let firstVideo123 = document.querySelector('#firstVideo');
            let canvas = document.getElementById("canvas"),
                context = canvas.getContext("2d");

            context.drawImage(firstVideo123, 0, 0, 640, 480);

            fetch('/by/upload', {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    name: new Date().getTime()+'.png',
                    data: convertCanvasToImage()
                })
            }).then(res => {
                return res.json()
            }).then(data => {
                console.log('图片上传结果', data)
            })

            console.log('image', convertCanvasToImage())
        }
    </script>
</body>
</html>